package thread;

/*
  有效的缩小同步范围可以在保证并发安全的前提下尽可能的提高并发效率。
  同步块:
  synchronized
 */
public class SyncDemo2 {
    public static void main(String[] args) {
        Shop shop = new Shop();
        Shop shop1 = new Shop();
        Thread t1 = new Thread("张三"){
            public void run(){
                shop.buy();
            }
        };
        Thread t2 = new Thread("王五"){
            public void run(){
                shop1.buy();
            }
        };
        t1.start();
        t2.start();
    }
}

class Shop{
    public void buy(){
        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName()+":正在挑选衣服...");
            Thread.sleep(5000);

            //同步块使用时必须在synchronized()中制定同步监视器对象，该对象必须满足两点:
            //1:必须是引用类型的实例
            //2:多个线程看到的必须是同一个对象
            synchronized (this) { //()里面是同步监视器对象
                System.out.println(t.getName() + "正在试衣服...");
                Thread.sleep(5000);
                System.out.println("结账离开");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
